import React from 'react';
import PropTypes from 'prop-types';
import { remove } from '../../services/sysPermission';
import { isSuccess } from '../../configs/error';
import { connect } from 'dva';
import Modal from './modal';
import shouldComponentUpdate from '../../components/decorator/shouldComponentUpdate';
import PermissionTree from './permissionTree';


@shouldComponentUpdate
class SysPermission extends React.Component {

	edit = (t, vls) => {
		if (t && !t.id) return;
		const { dispatch } = this.props;
		dispatch({
			type: 'sysPermission/set',
			payload: {
				currentItem: t,
				versionList: vls
			}
		});
	}

	delete = t => {
		// 删除
		if (!t.id) return;
		const { dispatch } = this.props;
		dispatch({
			type: 'sysPermission/deleteAndRefresh',
			id: t.id
		});
	}

	add = t => {
		// 新增一个子权限
		if (!t.id && t.id !== 0) return;

		const { dispatch } = this.props;
		dispatch({
			type: 'sysPermission/edit',
			payload: {
				id: null,
				icon: '',
				pPermissionId: t.id,
				permissionName: '',
				permissionType: 1,
				uri: '',
				permissionKey: ''
			}
		});
	}
	onDrop = async (info) => {
		const { sysPermission } = this.props;
		const { list } = sysPermission;
		const drapKey = info.dragNode.props.eventKey;
		const intoKey = info.node.props.eventKey;
		const drap = list.find(v => v.id === Number(drapKey));
		const res = await remove([drap.id]);
		if (isSuccess(res)) {
			const { dispatch } = this.props;
			const { icon, permissionKey, permissionName, permissionType, uri } = drap;
			const target = { ...drap };
			delete target.id;
			target.pPermissionId = intoKey * 1;
			// await new Promise(res=>setTimeout(res,1000))
			dispatch({
				type: 'sysPermission/createAndRefresh',
				payload: target
			});
		}
	}

	handleOk = t => {
		// 保存更改
		const { dispatch } = this.props;
		const action = {
			type: 'sysPermission/createAndRefresh',
			payload: t
		};
		if (t.id) {
			action.type = 'sysPermission/updateAndRefresh';
		}
		dispatch(action);
	}

	render() {
		const { sysPermission, loading, isAdmin } = this.props;
		const {
			list, currentItem, versionList
		} = sysPermission;
		// console.log(list.find(l => l.pPermissionId == '264'));

		// 不是admin隐藏版本权限
		let pList = [];
		if (isAdmin) pList = list;
		else pList = list.filter(v => v.permissionKey);
		return (
			<div className="content-inner">
				<PermissionTree
					list={list}
					isAdmin={isAdmin}
					edit={this.edit}
					delete={this.delete}
					add={this.add}
					onDrop={this.onDrop}
				/>
				<Modal
					data={currentItem}
					isAdmin={isAdmin}
					versionList={versionList}
					onOk={this.handleOk}
					handleCancel={() => this.edit(null, null)}
				/>
			</div>
		);
	}
}

SysPermission.propTypes = {
	sysPermission: PropTypes.object,
	location: PropTypes.object,
	dispatch: PropTypes.func,
	loading: PropTypes.object,
};

export default connect(({ sysPermission, app, loading }) => ({ sysPermission, isAdmin: app.user.isAdmin, loading }))(SysPermission);
